package com.tanhua.dubbo.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.domain.db.*;
import com.tanhua.domain.mongo.Report;

import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.SoulApi;
import com.tanhua.dubbo.mapper.*;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.*;

@Service
public class SoulApiImpl implements SoulApi {
    @Autowired
    private TestQuestionMapper testQuestionMapper;
    @Autowired
    private OptionMapper optionMapper;
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ConclusionMapper conclusionMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    //展示问题列表
    @Override
    public List<QuestionVo> showQuestions(Long userId) {

        Query query1 = new Query(Criteria.where("userId").is(userId).and("state").is(1));
        Report report1 = mongoTemplate.findOne(query1, Report.class);
        Query query2 = new Query(Criteria.where("userId").is(userId).and("state").is(2));
        Report report2 = mongoTemplate.findOne(query2, Report.class);
        Query query3 = new Query(Criteria.where("userId").is(userId).and("state").is(3));
        Report report3 = mongoTemplate.findOne(query3, Report.class);

        QueryWrapper<Questionnaire> questionnaireQueryWrapper=new QueryWrapper<>();

        List<Questionnaire> questionnaireList = questionnaireMapper.selectList(questionnaireQueryWrapper);
        List<QuestionVo>  questionVoList=new ArrayList<>();
        for (Questionnaire questionnaire : questionnaireList) {
            QueryWrapper<TestQuestion> testQuestionQueryWrapper=new QueryWrapper<>();
            testQuestionQueryWrapper.eq("qid",questionnaire.getId());

            List<TestQuestion> testQuestionList = testQuestionMapper.selectList(testQuestionQueryWrapper);

            List<Questions> questionsList=new ArrayList<>();
            for (TestQuestion testQuestion : testQuestionList) {
                QueryWrapper<Option> optionQueryWrapper= new QueryWrapper<>();
                optionQueryWrapper.eq("qid",questionnaire.getId()).eq("tid",testQuestion.getId());

                List<Option> optionList = optionMapper.selectList(optionQueryWrapper);
                List<Options> optionsList=new ArrayList<>();
                for (Option option : optionList) {
                    Options options = new Options();
                    options.setId(option.getId().toString());
                    options.setOption(option.getOptions());
                    optionsList.add(options);
                }
                Questions questions = new Questions();
                questions.setId(testQuestion.getId().toString());
                questions.setQuestion(testQuestion.getQuestion());
                questions.setOptions(optionsList);
                questionsList.add(questions);

            }

            QuestionVo questionVo = new QuestionVo();
            BeanUtils.copyProperties(questionnaire,questionVo);
            questionVo.setId(questionnaire.getId().toString());
            if(report3!=null){
                questionVo.setIsLock(0);
                switch (questionnaire.getId()){
                    case 1:
                        questionVo.setReportId(report1.getId().toString());
                        break;
                    case 2:
                        questionVo.setReportId(report2.getId().toString());
                        break;
                    case 3:
                        questionVo.setReportId(report3.getId().toString());
                        break;
                }
            }else if (report2!=null){
                switch (questionnaire.getId()){
                    case 1:
                        questionVo.setIsLock(0);
                        questionVo.setReportId(report1.getId().toString());
                        break;
                    case 2:
                        questionVo.setIsLock(0);
                        questionVo.setReportId(report2.getId().toString());
                        break;
                    case 3:
                        questionVo.setIsLock(0);
                        questionVo.setReportId(null);
                        break;
                }
            }else if(report1!=null) {
                switch (questionnaire.getId()) {
                    case 1:
                        questionVo.setIsLock(0);
                        questionVo.setReportId(report1.getId().toString());
                        break;
                    case 2:
                        questionVo.setIsLock(0);
                        questionVo.setReportId(null);
                        break;
                    case 3:
                        questionVo.setIsLock(1);
                        questionVo.setReportId(null);
                        break;
                }
            }else {
                if(questionnaire.getId()==1){

                    questionVo.setIsLock(0);

                }else {
                    questionVo.setIsLock(1);
                }
                questionVo.setReportId(null);

            }


            questionVo.setQuestions(questionsList);
            questionVoList.add(questionVo);
        }

        return questionVoList;
    }



    //保存报告结果
    @Override
    public ObjectId saveReport(Long userId, int score, Integer conclusion,Integer state) {
        Query query = new Query(Criteria.where("userId").is(userId).and("state").is(state));
        Report report = mongoTemplate.findOne(query, Report.class);
        if(report==null){
            report = new Report();

            report.setScore(score);
            report.setUserId(userId);


            report.setConclusionId(conclusion);
            report.setState(state);
            mongoTemplate.save(report);
        }else {
            Update update = new Update();
            update.set("conclusionId",conclusion);
            update.set("score",score);

            mongoTemplate.updateFirst(query,update,Report.class);
        }



        return report.getId();
    }
   //查询报告结果
    @Override
    public ReportVo queryResult(String id) {
        Query query = new Query(Criteria.where("_id").is(id));

        Report report = mongoTemplate.findOne(query, Report.class);
        ReportVo reportVo = new ReportVo();
        if(report!=null) {
            QueryWrapper<Conclusion> conclusionQueryWrapper = new QueryWrapper<>();
            conclusionQueryWrapper.eq("id",report.getConclusionId());
            Conclusion conclusion = conclusionMapper.selectOne(conclusionQueryWrapper);

            reportVo.setCover(conclusion.getCover());
            reportVo.setConclusion(conclusion.getConclusions());
            List<Similar> similarList=new ArrayList<>();
            Random random = new Random();

            for (int i = 2; i < 11; i++) {
                int r = random.nextInt(100);
                UserInfo userInfo = userInfoMapper.selectById(r);
                Similar similar = new Similar();
                if(userInfo!=null){
                    similar.setAvatar(userInfo.getAvatar());
                    similar.setId(userInfo.getId());
                }


                similarList.add(similar);
            }


            int num1 = random.nextInt(50) + 50;
            Dimension dimension = new Dimension();
            dimension.setKey("外向");
            dimension.setValue(num1+"%");
            int num2 = random.nextInt(50) + 50;
            Dimension dimension1 = new Dimension();
            dimension1.setKey("判断");
            dimension1.setValue(num2+"%");
            int num3 = random.nextInt(50) + 50;
            Dimension dimension2 = new Dimension();
            dimension2.setKey("抽象");
            dimension2.setValue(num3+"%");
            int num4 = random.nextInt(50) + 50;
            Dimension dimension3 = new Dimension();
            dimension3.setKey("理性");
            dimension3.setValue(num4+"%");
            List<Dimension> dimensionList = new ArrayList<>();
            dimensionList.add(dimension);
            dimensionList.add(dimension1);
            dimensionList.add(dimension2);
            dimensionList.add(dimension3);
            reportVo.setSimilarYou(similarList);
            reportVo.setDimensions(dimensionList);
        }
        return reportVo;
    }
    //查询每个选项的分数
    @Override
    public Map<String, Integer> queryScore(Map<String, List<Map<String, String>>> answers) {
        int sum=0;
        Map<String, Integer> param=new HashMap<>();
        List<Map<String, String>> paramMap = answers.get("answers");
        if(paramMap!=null){
            for (Map<String, String> map : paramMap) {
                //得到试题号
                String questionId = map.get("questionId");
                //得到选项号
                String optionId = map.get("optionId");
                int qid = Integer.parseInt(questionId);
                int oid = Integer.parseInt(optionId);
                QueryWrapper<Option> optionQueryWrapper = new QueryWrapper<>();
                optionQueryWrapper.eq("tid",qid).eq("id",oid);
                //得到选项
                Option option = optionMapper.selectOne(optionQueryWrapper);
                if(qid<11){
                    sum +=option.getScore();
                    param.put("state",1);
                    param.put("score",sum);
                }else if(qid<21){
                    sum +=option.getScore();
                    param.put("state",2);
                    param.put("score",sum);
                }else {
                    sum +=option.getScore();
                    param.put("state",3);
                    param.put("score",sum);
                }

            }
        }
        return param;
    }


}
